package com.quanquan.store.controller.marketActivity;

import DTO.PageDTO;
import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.quanquan.store.dto.ConsumeDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.marketActivity.TurnTableDTO;
import com.quanquan.store.dto.marketActivity.TurnTableGiftDTO;
import com.quanquan.store.entity.marketActivity.GiftTypeEnum;
import com.quanquan.store.entity.marketActivity.turnTable.*;
import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.request.marketActivity.TurnTableRequest;
import com.quanquan.store.service.CouponService;
import com.quanquan.store.service.marketActivity.TurnTableService;
import enums.ResCodeEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.HttpUtils;
import utils.StringUtil;
import utils.StringUtils;
import web.response.ResultBody;

import java.util.*;

/**
 * @ClassName TurnTableController
 * @Description
 * @Author Owen
 * @Date 2019/9/19 0019 上午 10:38
 * @Version V1.0
 **/
@RestController
@RequestMapping("/marketActivity/turnTable")
@Log4j2
public class TurnTableController {

    @Value("${module-url.userUrl}")
    private String userUrl;

    @Autowired
    private TurnTableService turnTableService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取游戏信息
     * @param request
     * @return
     */
    @PostMapping("/getActivityInfo")
    public ResultBody getActivityInfo(@RequestBody TurnTableRequest request) {

        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        TurnTable turnTable = turnTableService.getById(request.getId());
        if (null == turnTable || turnTable.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        //进行中
        Integer goingStatus = 0;
        if(turnTable.getStartTime().after(new Date())){
            goingStatus = -1;//未开始
        }
        if(turnTable.getEndTime().before(new Date())){
            goingStatus = 1;//已结束
        }

//        turnTableService.addUserChance(request.getId(),request.getUserId());

        Integer chance = 0;
        TurnTableChance turnTableChance = turnTableService.getByIdAndUserId(turnTable.getId(), request.getUserId());
        if(null != turnTableChance){
            chance = turnTableChance.getChance();
        }

        TurnTableDTO turnTableDTO = new TurnTableDTO();
        BeanUtils.copyProperties(turnTable, turnTableDTO);
        turnTableDTO.setGoingStatus(goingStatus);
        turnTableDTO.setChance(chance);

        List<TurnTableGiftDTO> gifts = new LinkedList<>();
        List<TurnTableGift> giftList = turnTableService.getGiftsByActivityId(turnTable.getId(),1);
        for (TurnTableGift gift:giftList) {
            TurnTableGiftDTO turnTableGiftDTO = new TurnTableGiftDTO();
            turnTableGiftDTO.setGiftId(gift.getId());
            turnTableGiftDTO.setGiftName(gift.getName());
            turnTableGiftDTO.setGiftIndex(gift.getGiftIndex());
            gifts.add(turnTableGiftDTO);
        }

        turnTableDTO.setGifts(gifts);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", turnTableDTO);

    }


    /**
     * 获取抽奖结果
     * @param request
     * @return
     */
    @PostMapping("/getActivityGift")
    public ResultBody getActivityGift(@RequestBody TurnTableRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        TurnTable turnTable = turnTableService.getById(request.getId());
        if (null == turnTable || turnTable.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        if(turnTable.getStartTime().after(new Date())){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动未开始");
        }
        if(turnTable.getEndTime().before(new Date())){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动已结束");
        }

        TurnTableChance turnTableChance = turnTableService.getByIdAndUserId(turnTable.getId(), request.getUserId());
        if(null == turnTableChance || turnTableChance.getChance() <= 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "您的参与次数已用完");
        }

        TurnTableGift gift = null;
        List<TurnTableGift> gifts = turnTableService.getGiftsByActivityIdForGame(request.getId());

        if(gifts.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动已结束，敬请期待下次活动");
        }

        turnTableChance.setChance(turnTableChance.getChance() -1);
        turnTableChance = turnTableService.saveOrUpdateChance(turnTableChance);

        Integer sumGiftOdds = turnTableService.sumGiftOdds(turnTable.getId());

        int randOdds = (int)(Math.random()*sumGiftOdds + 1);

        int odds = 0;
        for (int i = 0; i < gifts.size(); i++) {
            odds += gifts.get(i).getOdds();
            if(odds >= randOdds){
                gift = gifts.get(i);
                break;
            }
        }

        System.out.println("随机奖品信息："+ JSON.toJSONString(gift));

        int giftId = 0;
        String giftName = "很遗憾，未中奖";
        TurnTableRecord record = new TurnTableRecord();
        record.setUserId(request.getUserId());
        record.setActivityId(request.getId());
        record.setActivityType(1);
        record.setCreateTime(new Date());
        if(null == gift){
            gift = turnTableService.getOneNoGift(request.getId());
            if(null != gift){
                giftName = gift.getName();
                giftId = gift.getId().intValue();
                record.setGiftId(gift.getId());
            }
            record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
        }else{
            record.setGiftId(gift.getId());
            giftId = gift.getId().intValue();
            GiftTypeEnum giftType = GiftTypeEnum.getGiftType(gift.getGiftType());
            switch (giftType){
                case COUPON_GIFT:
                    CouponRequest couponRequest = new CouponRequest();
                    couponRequest.setUserId(request.getUserId());
                    couponRequest.setId(gift.getCouponId());
                    String sendResult = couponService.sendCoupon(couponRequest);
                    System.out.println("发券结果："+sendResult);
                    if("发券成功".equals(sendResult)){
                        //扣减库存
                        turnTableService.substractGiftStock(gift.getId());
                        giftName = gift.getName();
                        record.setGiftType(GiftTypeEnum.COUPON_GIFT.getCode());
                        record.setCouponId(gift.getCouponId());
                    }else{
                        gift = turnTableService.getOneNoGift(request.getId());
                        if(null != gift){
                            giftName = gift.getName();
                            giftId = gift.getId().intValue();
                            record.setGiftId(gift.getId());
                        }
                        record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    }
                    break;
                case POINT_GIFT:
                    break;
                default:
                    record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    break;
            }
        }

        record = turnTableService.saveOrUpdateRecord(record);
        Map<String,Object> result = new HashMap<>();
        result.put("giftId",giftId);
        result.put("giftIndex",gift.getGiftIndex());
        result.put("giftName",giftName);
        result.put("giftType",record.getGiftType());
        result.put("chance",turnTableChance.getChance());

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);

    }

    /**
     * 分页获取活动记录
     * @param request
     * @return
     */
    @PostMapping("/getActivityRecord")
    public ResultBody getActivityRecord(@RequestBody TurnTableRequest request){
        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        int page = request.getPage() == null ? 0 : request.getPage();
        int size = request.getSize() == null ? 20 : request.getSize();

        List<TurnTableRecord> recordList = turnTableService.getTurnRecordList(request.getId(),1, page, size);

        List<Object> result = new LinkedList<>();
        TurnTableRequest turnTableRequest = null;
        Map<String,Object> map = null;
        for (TurnTableRecord record : recordList) {
            map = new HashMap<>();
            TurnTableGift turnTableGift = turnTableService.getByGiftId(record.getGiftId());
            if(null == turnTableGift){
                continue;
            }
            map.put("giftName",turnTableGift.getName());

            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(record.getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                continue;
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO){
                continue;
            }
            map.put("phone",userDTO.getPhone().substring(0, 3) + "****" + userDTO.getPhone().substring(7, userDTO.getPhone().length()));

            result.add(map);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);
    }


    /**
     * 获取大屏倒计时及往期记录
     * @param request
     * @return
     */
    @PostMapping("/getBigScreenInfo")
    public ResultBody getBigScreenInfo(@RequestBody TurnTableRequest request){
        Calendar calendar  = Calendar.getInstance();
        calendar.setTime(new Date());
        if(calendar.get(calendar.MINUTE) >= 28){
            calendar.add(Calendar.HOUR_OF_DAY,1);
        }
        calendar.set(calendar.MINUTE,28);
        calendar.set(calendar.SECOND,0);
        calendar.set(calendar.MILLISECOND,0);
        Long countDown = (calendar.getTime().getTime() - new Date().getTime())/1000;

        List<Object> recordList = new LinkedList<>();
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> map = null;
        List<TurnTableRecord> turnRecordList = turnTableService.getTurnRecordList(request.getId(), 2, 0, 50);
        for (TurnTableRecord record : turnRecordList) {
            map = new HashMap<>();
            TurnTableGift turnTableGift = turnTableService.getByGiftId(record.getGiftId());
            if(null == turnTableGift){
                continue;
            }
            map.put("giftName",turnTableGift.getName());

            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(record.getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                continue;
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO){
                continue;
            }
            map.put("phone",userDTO.getPhone().substring(0, 3) + "****" + userDTO.getPhone().substring(7, userDTO.getPhone().length()));
            map.put("giftTime", DateUtils.dateToString(record.getCreateTime(), DateUtils.TIMESTAMP));
            recordList.add(map);
        }

        resultMap.put("countDown",countDown);
        resultMap.put("recordList",recordList);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",resultMap);

    }

    /**
     * 获取大屏抽奖结果
     * @param request
     * @return
     */
    @PostMapping("/getBigScreenResult")
    public ResultBody getBigScreenResult(@RequestBody TurnTableRequest request){
        Calendar calendar  = Calendar.getInstance();
        calendar.setTime(new Date());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //判断当前时间段是否已经抽过奖
        List<TurnTableRecord> recordByHour = turnTableService.getBigRecordByHour(request.getId(),hour);
        if(recordByHour.size() > 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "当前时段已经开过奖");
        }

        //判断当前时段是否有奖品
        List<TurnTableGift> giftByHour = turnTableService.getBigGiftByHour(request.getId(),hour);
        if(giftByHour.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "当前时段无奖品");
        }

        List<TurnTableRecord> recordList = turnTableService.getTurnRecordForBig(request.getId());
        if(recordList.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "当前时段抽奖条件不允许");
        }

        //打乱集合
        Collections.shuffle(recordList);

        //从打乱的集合中取30条数据用于前端效果展示
        List<TurnTableRecord> showRecordList = null;
        if(recordList.size() >= 30 ){
            showRecordList = recordList.subList(0, 30);
        }else{
            showRecordList = recordList;
        }
        List<String> phoneList = new LinkedList<>();
        for (int i = 0; i < showRecordList.size(); i++) {
            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(showRecordList.get(i).getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                continue;
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO){
                continue;
            }
            phoneList.add(userDTO.getPhone().substring(0, 3) + "****" + userDTO.getPhone().substring(7, userDTO.getPhone().length()));
        }
        List<String> giftPhoneList = new LinkedList<>();
        for (int i = 0; i <giftByHour.size() ; i++) {
            String phone = addRandomPhoneGift(recordList, request.getId(), giftByHour.get(i).getId(),hour);
            if(null == phone){
                continue;
            }else{
                giftPhoneList.add(phone.substring(0,3) + "****" + phone.substring(7,phone.length()));
            }
        }

        if(giftPhoneList.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "抽奖号码查询失败");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("showPhoneList",phoneList);
        map.put("giftPhoneList",giftPhoneList);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",map);
    }


    public String addRandomPhoneGift(List<TurnTableRecord> recordList, Long activityId,Long giftId,int timeIndex){
        if(recordList.size() < 1){
            return null;
        }else{
            Random random = new Random();
            int i = random.nextInt(recordList.size());
            TurnTableRecord turnTableRecord = recordList.get(i);

            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(turnTableRecord.getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                recordList.remove(i);
                return addRandomPhoneGift(recordList,activityId,giftId,timeIndex);
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO){
                recordList.remove(i);
                return addRandomPhoneGift(recordList,activityId,giftId,timeIndex);
            }

            List<TurnTableRecord> bigRecordList = turnTableService.getTurnRecordByUserIdAndActivityType(turnTableRecord.getUserId(), activityId, 2);
            if(bigRecordList.size() > 0){
                recordList.remove(i);
                return addRandomPhoneGift(recordList,activityId,giftId,timeIndex);
            }else{

                TurnTableGift gift = turnTableService.getByGiftId(giftId);
                if(null == gift){
                    return null;
                }else{
                    TurnTableRecord record = new TurnTableRecord();
                    record.setUserId(turnTableRecord.getUserId());
                    record.setActivityId(activityId);
                    record.setCreateTime(new Date());
                    record.setGiftId(giftId);
                    record.setActivityType(2);
                    record.setTimeIndex(timeIndex);
                    GiftTypeEnum giftType = GiftTypeEnum.getGiftType(gift.getGiftType());
                    switch (giftType){
                        case COUPON_GIFT:
                            CouponRequest couponRequest = new CouponRequest();
                            couponRequest.setUserId(turnTableRecord.getUserId());
                            couponRequest.setId(gift.getCouponId());
                            String sendResult = couponService.sendCoupon(couponRequest);
                            System.out.println("发券结果："+sendResult);
                            if("发券成功".equals(sendResult)){
                                //扣减库存
                                turnTableService.substractGiftStock(gift.getId());
                                record.setGiftType(GiftTypeEnum.COUPON_GIFT.getCode());
                                record.setCouponId(gift.getCouponId());
                            }else{
                                return null;
                            }
                            break;
                        case POINT_GIFT:
                            break;
                        default:
                            record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                            break;
                    }

                    turnTableService.saveOrUpdateRecord(record);
                }
            }

            return userDTO.getPhone();
        }
    }


    /**
     * 后台列表
     * @param request
     * @return
     */
    @PostMapping("/getAllActivityList")
    public ResultBody getAllActivityList(@RequestBody TurnTableRequest request){
        PageDTO pageDTO = turnTableService.findAllActivityByPage(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",pageDTO);
    }

    /**
     * 添加或者修改活动信息
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public ResultBody edit(@RequestBody TurnTableRequest request){

        System.out.println(JSON.toJSONString(request));
        TurnTable turnTable = null;
        if(null == request.getId()){
            turnTable = new TurnTable();
            turnTable.setCreateTime(new Date());
        }else{
            turnTable = turnTableService.getById(request.getId());
            if(null == turnTable){
                return new ResultBody(ResCodeEnum.CUSTOM.getCode(),"活动信息查询失败");
            }

            if(request.getStatus() == 2){
                turnTable.setStatus(request.getStatus());
                turnTableService.saveOrUpdateTurnTable(turnTable);
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
            }


        }
        turnTable.setName(request.getName());
        turnTable.setDescription(request.getDescription());
        turnTable.setStatus(request.getStatus());
        turnTable.setStartTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getStartTime()));
        turnTable.setEndTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getEndTime()));

        turnTableService.saveOrUpdateTurnTable(turnTable);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
    }

    /**
     * 后台获取信息
     * @param request
     * @return
     */
    @PostMapping("/getInfoById")
    public ResultBody getInfoById(@RequestBody TurnTableRequest request) {

        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        TurnTable turnTable = turnTableService.getById(request.getId());

        if (null == turnTable) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", turnTable);

    }

    /**
     * 后台获取活动奖项列表
     * @param request
     * @return
     */
    @PostMapping("/getActivityGifts")
    public ResultBody getActivityGifts(@RequestBody TurnTableRequest request){
        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PageDTO pageDTO = turnTableService.getAllGifts(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", pageDTO);
    }

    @PostMapping("/editGift")
    public ResultBody editGift(@RequestBody TurnTableRequest request){
        System.out.println(JSON.toJSONString(request));
        TurnTableGift turnTableGift = null;
        if(null == request.getId()){
            turnTableGift = new TurnTableGift();
            turnTableGift.setCreateTime(new Date());
            turnTableGift.setRemainTotal(request.getSumTotal());
            turnTableGift.setActivityId(request.getActivityId());
        }else{
            turnTableGift = turnTableService.getByGiftId(request.getId());
            if(null == turnTableGift){
                return new ResultBody(ResCodeEnum.CUSTOM.getCode(),"信息查询失败");
            }

            if(request.getStatus() == 2){
                turnTableGift.setStatus(request.getStatus());
                turnTableService.saveOrUpdateGift(turnTableGift);
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
            }


        }
        turnTableGift.setName(request.getName());
        turnTableGift.setSumTotal(request.getSumTotal());
        turnTableGift.setOdds(request.getOdds());
        turnTableGift.setCouponId(request.getCouponId());
        turnTableGift.setGiftType(request.getGiftType());
        turnTableGift.setPoints(request.getPoints());
        turnTableGift.setStatus(request.getStatus());
        turnTableGift.setActivityType(1);
        turnTableGift.setStartTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getStartTime()));
        turnTableGift.setEndTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getEndTime()));

        turnTableService.saveOrUpdateGift(turnTableGift);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
    }

    /**
     * 后台获取奖项详情
     * @param request
     * @return
     */
    @PostMapping("/getGiftInfoById")
    public ResultBody getGiftInfoById(@RequestBody TurnTableRequest request) {

        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        TurnTableGift turnTableGift = turnTableService.getByGiftId(request.getId());

        if (null == turnTableGift) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "信息查询失败");
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", turnTableGift);

    }

    /**
     * 后台列表
     * @param request
     * @return
     */
    @PostMapping("/getRecordList")
    public ResultBody getRecordList(@RequestBody TurnTableRequest request){
        PageDTO pageDTO = turnTableService.findAllRecordByPage(request);
        log.info(JSON.toJSONString(pageDTO));
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",pageDTO);
    }
}
